package cumeo89.chii.client.form;

import static com.google.gwt.event.dom.client.KeyCodes.*;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ImageCaptchaDialog extends DialogBox implements KeyUpHandler {

	private SimplePanel pnlImage = new SimplePanel();
	private TextBox txtAnswer = new TextBox();
	private boolean cancelled = false;

	public ImageCaptchaDialog() {
		VerticalPanel pnlMain = new VerticalPanel();

		pnlMain.add(pnlImage);

		Label lblMess = new Label("Hãy nhập lại nội dung trong ảnh");
		pnlMain.add(lblMess);

		txtAnswer.addKeyUpHandler(this);
		pnlMain.add(txtAnswer);

		setWidget(pnlMain);
	}

	public void show(String url) {
		pnlImage.setWidget(new Image(url));
		cancelled = false;
		center();
		txtAnswer.setFocus(true);
	}

	public String getAnswer() {
		return cancelled ? null : txtAnswer.getText();
	}

	public void onKeyUp(KeyUpEvent event) {
		if (event.getSource() == txtAnswer) {
			if (event.getNativeKeyCode() == KEY_ENTER) {
				hide();
			} else if (event.getNativeKeyCode() == KEY_ESCAPE) {
				cancelled = true;
				hide();
			}
		}
	}

}
